package vip.xiaonuo.modular.xypdf.api;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vip.xiaonuo.core.annotion.BusinessLog;
import vip.xiaonuo.core.annotion.version.ApiVersionSwagger;
import vip.xiaonuo.core.enums.CodeStatus;
import vip.xiaonuo.core.enums.LogAnnotionOpTypeEnum;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.pojo.response.SuccessResponseData;
import vip.xiaonuo.core.util.TencentCosUtil;
import vip.xiaonuo.modular.xylogy.service.XyLogyService;
import vip.xiaonuo.modular.xylogytemplate.entity.XyLogyTemplate;
import vip.xiaonuo.modular.xylogytemplate.service.XyLogyTemplateService;
import vip.xiaonuo.modular.xypdf.entity.XyPdf;
import vip.xiaonuo.modular.xypdf.form.PdfLogyGenderForm;
import vip.xiaonuo.modular.xypdf.param.XyPdfParam;
import vip.xiaonuo.modular.xypdf.service.XyPdfService;
import vip.xiaonuo.sys.core.cache.SmsCache;
import vip.xiaonuo.sys.core.cache.UserCache;
import vip.xiaonuo.sys.core.msg.Result;

import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static vip.xiaonuo.sys.core.msg.ResultUtils.fail;
import static vip.xiaonuo.sys.core.msg.ResultUtils.success;

@RestController
@Api(tags = "谱书相关apis")
@ApiVersionSwagger
@RequestMapping("/genealogybook")
public class ApiPdfController {

    @Autowired
    private XyPdfService xyPdfService;

    @Autowired
    private XyLogyTemplateService logyTemplateService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SmsCache smsCache;

    @GetMapping("/sendPhone/{phone}")
    @ApiOperation(value = "发送验证码")
    public Result sendPhone(@PathVariable String phone){
        if (!Validator.isMobile(phone))
            return fail(CodeStatus.ACCOUNT_FORMAT_ERROR);
        String code =  RandomUtil.randomInt(6)+ "" + RandomUtil.randomInt(6) + "" +RandomUtil.randomInt(6) + "" +RandomUtil.randomInt(6)+ "" +RandomUtil.randomInt(6)+ "" +RandomUtil.randomInt(6);

        Assert.isTrue(Objects.isNull(redisTemplate.opsForValue().get(phone)),"1分钟内不可在发送.");
        smsCache.put(phone,code,60L);
        return success(code);
    }

    @GetMapping("/checkPhone/{phone}/{code}")
    @ApiOperation(value = "发送验证码")
    public Result checkPhone(@PathVariable String phone,@PathVariable String code){
        String codes = smsCache.get(phone);
        if (StringUtils.isBlank(codes))
            fail(CodeStatus.TELPHONE_NO_VERIFICODE);//请去获取验证码
        if (!codes.equals(code))
            fail(CodeStatus.TELPHONE_CHECK_FAIL);
        return success();
    }



    @GetMapping("/pdfTemplate")
    @ApiOperation("pdf模板查询")
    public Result<List<XyLogyTemplate>> pdfTemplate(){
        return success(logyTemplateService.list());
    }


    @GetMapping("/byLogyId/{logyId}")
    @ApiOperation("根据家谱编号查询,生成的谱书")
    public Result<PageResult<XyPdf>> byLogyId(XyPdfParam xyPdfParam){
        XyLogyService xyLogyService = SpringUtil.getBean(XyLogyService.class);
        PageResult<XyPdf> page = xyPdfService.page(xyPdfParam);
        List<XyPdf> rows = page.getRows();
        for (XyPdf xyPdf : rows) {
            xyPdf.setXyLogy(xyLogyService.getById(xyPdf.getLogyId()));
        }
        return success(page);
    }

    @PostMapping("/genderPdfByLogyId")
    @ApiOperation(value = "根据pdf模板,以及族谱编号生成对应的pdf",notes = "生成对应的 资源链接,pdf格式")
    public Result<String> genderPdfByLogyId(@RequestBody @Validated PdfLogyGenderForm pdfLogyGenderForm){
        String pdfUrl =  xyPdfService.genderPdfByLogyId(pdfLogyGenderForm);
        return success(pdfUrl);
    }

    /**
     * 行传列表
     */
    @GetMapping("/pdf/open/lineChildList/{logyId}")
    @ApiOperation(value = "行传列表",notes = "行传列表 数据结构 为列表，已经排过序")
    public Result<JSONObject> pdfOpenLineChildList(@PathVariable String logyId){
        JSONObject lineLevelsLogyVos =  xyPdfService.pdfOpenLineChildList(logyId);
        return success(lineLevelsLogyVos);
    }

    /**
     * 行传列表
     */
    @GetMapping("/pdf/open/lineChildListOld/{logyId}")
    @ApiOperation(value = "行传列表",notes = "行传列表 数据结构 为列表，已经排过序")
    public Result<JSONObject> lineChildListOld(@PathVariable String logyId){
        JSONObject lineLevelsLogyVos =  xyPdfService.pdfOpenLineChildList(logyId);
        return success(lineLevelsLogyVos);
    }


    @PostMapping({"/v1/public/file/upload"})
    @BusinessLog(title = "文件信息表_上传文件", opType = LogAnnotionOpTypeEnum.OTHER)
    public ResponseData upload(@RequestPart("file") MultipartFile file,@RequestPart("pdfId") String pdfId) throws IOException {
        String s = TencentCosUtil.uploadInputfile(file.getInputStream(), file.getOriginalFilename());
        XyPdf xyPdf = xyPdfService.getById(pdfId);
        xyPdf.setPdfUrl(s);
        xyPdfService.updateById(xyPdf);
        return new SuccessResponseData(s);
    }


}
